<?php

namespace app\common\behavior;


use think\facade\Db;
use think\facade\Request;
use think\facade\Config;
// use think\facade\Session;

class AppInit
{
    public function handle($param = [])
    {
        // 事件监听处理
        if(!empty($param['uniacid'])){
            $uniacid = $param['uniacid'];
        }else if (Request::param('uniacid')) {
            $uniacid = Request::param('uniacid');
        } else if (Request::header('uniacid')) {
            $uniacid = Request::header('uniacid');
        } else if(cookie('uniacid')){
            $uniacid = cookie('uniacid');
        } else {
            $uniacid = 0;
        }

        if ($uniacid) {
            cookie('uniacid', $uniacid);
        }

        $url = preg_replace("/\/(\w+)\.php$/i", '', Request::root());


        if(Request::isCli()){
            $path = getcwd() . '/../../data/config.php';
        }else{
            $path = getcwd() . '/../../../data/config.php';
        }
        Config::set([
            'uniacid' => $uniacid, // 应用id
            'is_we7' => is_file($path), // 是否微擎环境
            'cdnurl' => $url,
        ], 'site');

        $database_config = Config::get('database');
        foreach ($database_config['connections'] as &$connection) {
            $connection['query'] = \we\ExtendQuery::class;
        }
        Config::set($database_config, 'database');

        $view_config = Config::get('view');
        $view_config['tpl_replace_string']['__CDN_URL__'] = $url;
        $view_config['tpl_replace_string']['__STATIC__'] = $url.'/resource';
        $view_config['tpl_replace_string']['__ADMIN__'] = $url.'/resource/admin';
        Config::set($view_config, 'view');

        // 只有首次执行
        // $this->fisrtRun();

        $this->initData();
    }

    public function fisrtRun()
    {
        $database_config = Config::get('database');

        $database = $database_config['connections'][$database_config['default']]['database'];
        $prefix = $database_config['connections'][$database_config['default']]['prefix'];

        $sql = "SELECT CONCAT('ALTER TABLE `', table_name, '` ADD COLUMN `uniacid` INT(11) NOT NULL DEFAULT 0 COMMENT \"应用id\"') as query FROM information_schema.TABLES WHERE table_schema = '" . $database . "'";
        $list = Db::query($sql);

        foreach ($list as $item) {
            Db::query($item['query']);
        }
    }

    // 进行初始数据的填充
    public function initData()
    {
        // 岗位
        $admin_role = Db::name('admin_role')->where('role_name', '超级管理员')->find();
        if(!$admin_role) {
            $role_id = Db::name('admin_role')->insertGetId([
                'role_name' => '超级管理员',
                'act_list' => 'all',
                'role_desc' => '管理全站',
            ]);
        }else{
            $role_id = $admin_role['role_id'];
        }


        // 管理员账号
        $admin_info = Db::name('admin')->where('user_name', 'admin')->find();
        if(!$admin_info) {
            Db::name('admin')->insertGetId([
                'user_name' => 'admin',
                'email' => 'all',
                'password' => 'd8b320458391d80996413030ce14f0ee', // admin123456
                'add_time' => time(),
                'last_login' => time(),
                'last_ip' => getIP(),
                'role_id' => $role_id,
            ]);
        }

        // 支付方式
        $plugin = Db::name('plugin')->where('id', '>', 1)->select();
        if($plugin->isEmpty()) {
            $database_config = config('database');
            $plugin_base_list = Db::query('select * from '. $database_config['connections']['mysql']['prefix'] .'plugin where uniacid=0');
            foreach ($plugin_base_list as $item){
                unset($item['id'], $item['config_value']);
                Db::name('plugin')->insert($item);
            }
        }

        // 协议 protocol
        $protocol = Db::name('protocol')->where('id', '>', 1)->select();
        if($protocol->isEmpty()) {
            $database_config = config('database');
            $protocol_base_list = Db::query('select * from '. $database_config['connections']['mysql']['prefix'] .'protocol where uniacid=0');
            foreach ($protocol_base_list as $item){
                unset($item['id']);
                Db::name('protocol')->insert($item);
            }
        }
    }

}
